import common from "shared/component/common/common";
import Log4R from "shared/component/log/Log4R";
import WallHeader from "shared/component/trigger/WallHeader";

import { Direction2D } from "shared/enums/UtilValue";
import { ScenceServiceImpl } from "shared/modules/director/service/ScenceServiceImpl";
const loginfo = Log4R.getLog('info');
const testConfig: Ctn.scence.ScenceConfig = {
    spaws: [
        "area1.spaw",
        "area2.spaw",
    ],
    src: "test",
    areas: {
        area2: {
            monster: {
                mon: {
                    character: "test",
                    AI: "test"
                }
            }
        },

    }
}
/** 场景默认的物理 */
const scencePartDefaultPhysicalProperties = new PhysicalProperties(1, 0, 0, 0, 0);
export default class ScenceServerServiceImpl extends ScenceServiceImpl {



    getCurrentScenceEntity() {
        return this.currentScenceEntity
    }
    /**
     * 加载场景
     * @param scence 场景名 
     */
    load(scenceEntity: Ctn.ScenceEntity) {
        /** 场景配置 */
        let scenceConfig: Ctn.scence.ScenceConfig | undefined
        if (scenceEntity.scenceId === 'test') {
            scenceConfig = testConfig
        }
        this.currentScenceEntity = undefined
        if (scenceConfig) {
            let scenceResource: Instance | undefined
            //判断使用素材场景还是使用服务器存储资源

            /** 游戏工作空间中的场景文件夹 */
            const gameScence = game.Workspace.FindFirstChild('scence');
            // loginfo?.info('gameScence', gameScence)
            // 判断开发环境是否有测试场景
            if (game.GetService('RunService').IsStudio() && gameScence && gameScence.GetChildren().size() > 0) {
                // loginfo?.info('gameScence.GetChildren()', gameScence.GetChildren())
                scenceResource = gameScence.GetChildren()[0];
            } else if (gameScence) {
                gameScence.ClearAllChildren();
                if (scenceConfig.url) {
                    // 未完成在线场景
                } else if (scenceConfig.src) {
                    scenceResource = game.GetService('ServerStorage').FindFirstChild('scence')?.FindFirstChild(scenceConfig.src);
                }
                if (!scenceResource) {
                    throw ('scence resource not find')
                }
                // 非开发环境 清除场景文件夹下的内容
                gameScence.GetChildren().forEach(c => c.Destroy())
                if (!scenceConfig.url) {
                    scenceResource = scenceResource.Clone();
                }
                scenceResource.Parent = gameScence;
            }
            if (!scenceResource) {
                throw ('scenceResource is not inited!')
            }
            /** 检测与左右上角部件碰撞的其他部件的条件 */
            const overlapParams = new OverlapParams();
            overlapParams.RespectCanCollide = true;
            /** 处理场景中的平台 */

            const setPhysicalFunction = (c: Instance) => {
                if (c.IsA('BasePart')) {
                    c.CustomPhysicalProperties = scencePartDefaultPhysicalProperties;
                }
                /** 处理墙头 */
                if (c.IsA('BasePart') && c.CanCollide && math.abs(c.CFrame.Position.Z) < 1) {
                    const cornerPartRight = new Instance('Part');
                    cornerPartRight.Size = new Vector3(1, 1, 1)
                    cornerPartRight.CanCollide = false;
                    // cornerPartRight.Anchored=true;
                    cornerPartRight.Name = "WallHeader";
                    cornerPartRight.Parent = c;
                    const weld = new Instance('WeldConstraint');
                    weld.Parent = c;
                    weld.Part0 = c;
                    weld.Part1 = cornerPartRight;
                    cornerPartRight.Position = c.CFrame.PointToWorldSpace(new Vector3(-c.Size.X / 2, c.Size.Y / 2, 0))
                    const cornerPartLeft = new Instance('Part');
                    cornerPartLeft.Size = new Vector3(1, 1, 1)
                    cornerPartLeft.CanCollide = false;
                    // cornerPartRight.Anchored=true;
                    cornerPartLeft.Name = "WallHeader";
                    cornerPartLeft.Parent = c;
                    const weldLeft = new Instance('WeldConstraint');
                    weldLeft.Parent = c;
                    weldLeft.Part0 = c;
                    weldLeft.Part1 = cornerPartLeft;
                    cornerPartLeft.Position = c.CFrame.PointToWorldSpace(new Vector3(c.Size.X / 2, c.Size.Y / 2, 0));
                    /** 检测与左右上角部件碰撞的其他部件 */
                    const partsInCornerPartRight = game.Workspace.GetPartsInPart(cornerPartRight, overlapParams);

                    if (partsInCornerPartRight.size() > 1) {
                        cornerPartRight.Destroy();
                        // loginfo?.info("^^^^^^^^^^^^^^^^^^^^检测与左右上角部件碰撞的其他部件^^^^^^^^^^^^^^^^^^^^^^^^")
                        // loginfo?.info("检测与左右上角部件碰撞的其他部件", cornerPartRight, 'partsInCornerPartRight', partsInCornerPartRight)
                        // loginfo?.info("vvvvvvvvvvvvvvvvvvvv检测与左右上角部件碰撞的其他部件vvvvvvvvvvvvvvvvvvvv")
                    } else {
                        WallHeader.addWallHead(cornerPartRight, Direction2D.Right)
                    }
                    const partsInCornerPartLeft = game.Workspace.GetPartsInPart(cornerPartLeft, overlapParams);
                    if (partsInCornerPartLeft.size() > 1) {
                        cornerPartLeft.Destroy();
                        // loginfo?.info("^^^^^^^^^^^^^^^^^^^^检测与左右上角部件碰撞的其他部件^^^^^^^^^^^^^^^^^^^^^^^^")
                        // loginfo?.info("检测与左右上角部件碰撞的其他部件", cornerPartRight, 'partsInCornerPartRight', partsInCornerPartRight)
                        // loginfo?.info("vvvvvvvvvvvvvvvvvvvv检测与左右上角部件碰撞的其他部件vvvvvvvvvvvvvvvvvvvv")
                    } else {
                        WallHeader.addWallHead(cornerPartLeft, Direction2D.Left)
                    }

                }
            }
            gameScence?.GetDescendants().forEach(setPhysicalFunction)
            gameScence?.DescendantAdded.Connect(setPhysicalFunction)
            this.currentScenceEntity = scenceEntity;
            scenceEntity.scenceInstance = scenceResource;
            scenceEntity.config = scenceConfig
            this.enableSpaw()
            loginfo?.info('syncCurrentScenceEntity——————》', this.currentScenceEntity)
            this.loadScenceBinder.callBack(scenceEntity)
        }
    }
    syncCurrentScenceEntity() {
        this.fire('syncCurrentScenceEntity', this.currentScenceEntity)
    }
    /** 启用出生点 */
    private enableSpaw(spawpath?: string) {
        if (!this.currentScenceEntity) {
            throw ('currentScenceEntity is null')
        }
        /** 场景实例 */
        const scenceInstance = this.currentScenceEntity.scenceInstance;
        if (scenceInstance)
            this.currentScenceEntity.config?.spaws.forEach((path, index) => {
                const spaw = common.getByPath<Instance>(path, scenceInstance);
                if (!spaw.IsA('SpawnLocation')) {
                    throw ('not a Spawn Location:' + spaw)
                }
                if (!spawpath) {
                    if (index === 0) {
                        spaw.Enabled = true
                    } else {
                        spaw.Enabled = false
                    }
                } else {
                    if (spawpath === path) {
                        spaw.Enabled = true
                    } else {
                        spaw.Enabled = false
                    }
                }
            })
    }
}